import {Message} from "@arco-design/web-vue";

class WsClient {
    constructor(uri) {
        this.uri = uri;
    }

    uri;
    socket;

    connected = false;

    connect(output) {
        let url = this.uri;
        url = window.wsUrlBase + url
        this.socket = new WebSocket(url);
        this.socket.onmessage = output;
        this.socket.onerror = this.error;
        this.socket.onopen = () => {
            this.connected = true;
            Message.info({content: "已连接ws", showIcon: true});
        }

    }

    /**
     * @param cmd 原始命令
     * */
    sendCmd(cmd) {
        this.socket.send(cmd);
    }

    sendRawCmd(sn, opcode, params) {
        let msg = {SN: sn, OP_CODE: opcode, PARAMS: params};
        this.sendCmd(JSON.stringify(msg));
    }

    /**
     * @param msg json字符串
     * */
    send(msg) {
        this.socket.send(msg);
    }

    error(eve) {
        console.log(eve)
        Message.error({content: 'ws连接失败,可能是切换了UA标识,请重新登录', showIcon: true})
    }

    isConnected(){
        return this.connected;
    }
}


export default WsClient